<template>
  <div class="cloud mbm">
    <a-form layout="inline" :form="formSettings" @submit.prevent="submitSettings">
      <div v-if="sub==1 || typeof sub=='undefined'">
        <h4 class="step_title mbm">云服务配置</h4>
        <div class="label">accessKeyId：</div>
        <div class="wrapper mbs">
          <a-form-item>
            <a-input
              class="talk_input mrm"
              style="width: 350px"
              placeholder="请输入阿里云accessKeyId"
              v-decorator="['aliyun_ak_id',{ rules: [{ required: true, message: '这里不能为空哦！' }] }]"
              v-on:blur="handleCheckAliyun"
            >
              <a-popover slot="suffix" title="帮助提示">
                <template slot="content">
                  此处填写阿里云API的密钥KeyId，
                  <a
                    target="_blank"
                    :href="this.$api.help.url.redirect+'?to=aliyunKey'"
                  >点此获取</a>
                </template>
                <a-icon
                  :type="icon[test.aliyunAccess].type"
                  theme="twoTone"
                  :twoToneColor="icon[test.aliyunAccess].color"
                />
              </a-popover>
            </a-input>
          </a-form-item>
        </div>
        <div class="label">accessKeySecret：</div>
        <div class="wrapper mbs">
          <a-form-item>
            <a-input
              class="talk_input mrm"
              style="width: 350px"
              placeholder="请输入阿里云accessKeySecret"
              v-decorator="['aliyun_ak_secret',{ rules: [{ required: true, message: '这里不能为空哦！' }] }]"
              v-on:blur="handleCheckAliyun"
            >
              <a-popover slot="suffix" title="帮助提示">
                <template slot="content">
                  此处填写阿里云API的密钥KeySecret，
                  <a
                    target="_blank"
                    :href="this.$api.help.url.redirect+'?to=aliyunKey'"
                  >点此获取</a>
                </template>
                <a-icon
                  :type="icon[test.aliyunAccess].type"
                  theme="twoTone"
                  :twoToneColor="icon[test.aliyunAccess].color"
                />
              </a-popover>
            </a-input>
          </a-form-item>
        </div>
        <div class="label">智能语音交互服务AppKey：</div>
        <div class="wrapper mbs">
          <a-form-item>
            <a-input
              class="talk_input mrm"
              style="width: 350px"
              placeholder="请输入阿里云智能语音交互服务AppKey"
              v-decorator="['aliyun_isi_appkey',{ rules: [{ required: true, message: '这里不能为空哦！' }] }]"
              v-on:blur="handleCheckAliyun"
            >
              <a-popover slot="suffix" title="帮助提示">
                <template slot="content">
                  此处填写阿里云智能语音交互服务的Appkey，
                  <a
                    target="_blank"
                    :href="this.$api.help.url.redirect+'?to=nls'"
                  >点此获取</a>
                </template>
                <a-icon
                  :type="icon[test.aliyunISIAppKey].type"
                  theme="twoTone"
                  :twoToneColor="icon[test.aliyunISIAppKey].color"
                />
              </a-popover>
            </a-input>
          </a-form-item>
        </div>
        <div class="mbm">
          <div class="wrapper">
            <a-checkbox
              :checked="upload_oss?'checked':''"
              @change="checkedUpload"
            >上传完整录音到OSS，执行更准确的云端分析</a-checkbox>
          </div>
          <div class="wrapper" v-show="upload_oss">
            <a-form-item>
              <a-auto-complete
                class="talk_input mrm"
                style="width: 350px"
                :dataSource="dataSource.oss"
                placeholder="请输入阿里云OSS云存储Bucket域名"
                v-decorator="['aliyun_bucket_name',{ rules: [] }]"
                @focus="handleListOSS"
                @blur="handleCheckAliyun"
                @select="handleCheckAliyun"
              >
                <a-input>
                  <a-popover slot="suffix" title="帮助提示">
                    <template slot="content">
                      此处填写阿里云OSS的Bucket域名，
                      <a
                        target="_blank"
                        :href="this.$api.help.url.redirect+'?to=oss'"
                      >点此获取</a>
                    </template>
                    <a-icon
                      :type="icon[test.aliyunOSS].type"
                      theme="twoTone"
                      :twoToneColor="icon[test.aliyunOSS].color"
                    />
                  </a-popover>
                </a-input>
              </a-auto-complete>
            </a-form-item>
          </div>
        </div>
      </div>
      <div v-if="sub==2 || typeof sub=='undefined'">
        <h4 class="step_title mbm">个性化设置：</h4>
        <div class="label">选择自己喜欢的发音</div>
        <div class="wrapper">
          <a-form-item>
            <a-select optionFilterProp="children" style="width: 350px" v-model="tts_voice">
              <a-select-option
                :value="v.Value"
                v-for="v in listTTS"
                :key="v.Value"
              >{{v.Name}} - {{v.Type}} - {{v.Note}}</a-select-option>
            </a-select>
          </a-form-item>
        </div>
        <div class="wrapper">
          <a-form-item label="语速">
            <a-row>
              <a-col :span="20">
                <a-slider style="width:300px;" :min="-500" :max="500" v-model="tts_speech" />
              </a-col>
              <a-col :span="4">
                <a-input-number :min="-500" :max="500" style="width:70px;" v-model="tts_speech" />
              </a-col>
            </a-row>
          </a-form-item>
        </div>
        <div class="wrapper">
          <a-form-item label="语调">
            <a-row>
              <a-col :span="20">
                <a-slider style="width:300px;" :min="-500" :max="500" v-model="tts_pitch" />
              </a-col>
              <a-col :span="4">
                <a-input-number :min="-500" :max="500" style="width:70px;" v-model="tts_pitch" />
              </a-col>
            </a-row>
          </a-form-item>
        </div>
        <div>
          <a-form-item label="音量">
            <a-row>
              <a-col :span="20">
                <a-slider style="width:300px;" :min="-500" :max="500" v-model="tts_volume" />
              </a-col>
              <a-col :span="4">
                <a-input-number :min="-500" :max="500" style="width:70px;" v-model="tts_volume" />
              </a-col>
            </a-row>
          </a-form-item>
        </div>
      </div>
      <div class="wrapper" v-if="sub==2 || typeof sub=='undefined'">
        <a-form-item>
          <a-popconfirm placement="topLeft" okText="修改" cancelText="取消" @confirm="setTextTTS">
            <template slot="title">
              <a-textarea
                v-model="tts_test"
                placeholder="请输入您想要转成语音的文本内容"
                :autosize="{ minRows: 2, maxRows: 6 }"
              />
            </template>
            <a-input :value="tts_test" class="tts_test"/>
          </a-popconfirm>
        </a-form-item>
        <a-form-item>
          <a-button type="dashed" @click="handleTestTTS" icon="sound">试听</a-button>
        </a-form-item>
        <div v-if="sound" class="wav_player mbm">
          <audio :src="sound" autoplay class="audio" controls></audio>
        </div>
      </div>
      <div v-if="typeof sub=='undefined'" class="mts">
        <a-form-item>
          <a-button class="mbm" type="primary" html-type="submit">立即修改</a-button>
        </a-form-item>
      </div>
    </a-form>
  </div>
</template>
<script>
export default {
  data() {
    const labelCol = {
      xs: { span: 5 },
      sm: { span: 5 }
    };
    const wrapperCol = {
      xs: { span: 24 },
      sm: { span: 12 }
    };
    return {
      formItemLayout: {
        labelCol,
        wrapperCol
      },
      buttonCol: {
        xs: { offset: labelCol.xs.span },
        sm: { offset: labelCol.sm.span }
      },
      dataSource: { oss: [], tts: [] },
      listTTS: [],
      sound: "",
      aliyun: { ak_id: "", ak_secret: "", isi_appkey: "" },
      upload_oss: false,
      tts_voice: "Xiaoyun",
      tts_speech: 0,
      tts_pitch: 0,
      tts_volume: 0,
      tts_test: "您好，欢迎使用智能语音助手！",
      test: {
        aliyunAccess: 2,
        aliyunISIAppKey: 2,
        aliyunOSS: 2,
        aliyunTTS: 2
      },
      icon: [
        { type: "check-circle", color: "#06b400" },
        { type: "exclamation-circle", color: "#ff0000" },
        { type: "question-circle", color: "#ccc" }
      ],
      formCheck: 2
    };
  },
  props: {
    sub: Number
  },

  created() {
    this.getValue();
  },
  watch: {
    $route() {
      this.getValue();
    }
  },
  methods: {
    getValue() {
      let setting = this.$store.state.common.setting;
      if (typeof setting.aliyun_ak_id != "undefined")
        this.aliyun.ak_id = setting.aliyun_ak_id;
      if (typeof setting.aliyun_ak_secret != "undefined")
        this.aliyun.ak_secret = setting.aliyun_ak_secret;
      if (typeof setting.aliyun_isi_appkey != "undefined")
        this.aliyun.isi_appkey = setting.aliyun_isi_appkey;
      if (typeof setting.aliyun_bucket_name != "undefined")
        this.aliyun.bucket_name = setting.aliyun_bucket_name;
      if (typeof setting.upload_oss != "undefined")
        this.upload_oss = setting.upload_oss;
      if (typeof setting.tts_voice != "undefined")
        this.tts_voice = setting.tts_voice;
      if (typeof setting.tts_speech != "undefined")
        this.tts_speech = parseInt(setting.tts_speech);
      if (typeof setting.tts_pitch != "undefined")
        this.tts_pitch = parseInt(setting.tts_pitch);
      if (typeof setting.tts_volume != "undefined")
        this.tts_volume = parseInt(setting.tts_volume);
      if (typeof setting.tts_test != "undefined")
        this.tts_test = parseInt(setting.tts_test);
      this.formSettings = this.$form.createForm(this, {
        name: "form_settings",
        mapPropsToFields: () => {
          return {
            aliyun_ak_id: this.$form.createFormField({
              value: this.aliyun.ak_id
            }),
            aliyun_ak_secret: this.$form.createFormField({
              value: this.aliyun.ak_secret
            }),
            aliyun_isi_appkey: this.$form.createFormField({
              value: this.aliyun.isi_appkey
            }),
            aliyun_bucket_name: this.$form.createFormField({
              value: this.aliyun.bucket_name
            }),
            tts_test: this.$form.createFormField({
              value: this.tts_test
            })
          };
        }
      });
      if (this.sub == 1) {
        this.formCheck = 2;
      }
      if (this.sub == 2) {
        this.formCheck = 0;
      }
      if (typeof sub == "undefined" || this.sub == 2) {
        this.$api.setting.getTTSList().then(res => {
          this.listTTS = res;
        });
      }
    },
    formToData(values, cacheISI) {
      let data = [];
      let setting = this.$store.state.common.setting;
      if (cacheISI != "undefined") {
        cacheISI = true;
      }

      if (typeof values.aliyun_ak_id != "undefined") {
        data.push({
          key: "aliyun_ak_id",
          value: values.aliyun_ak_id
        });
      } else if (cacheISI) {
        data.push({
          key: "aliyun_ak_id",
          value: setting.aliyun_ak_id
        });
      }
      if (typeof values.aliyun_ak_secret != "undefined") {
        data.push({
          key: "aliyun_ak_secret",
          value: values.aliyun_ak_secret
        });
      } else if (cacheISI) {
        data.push({
          key: "aliyun_ak_secret",
          value: setting.aliyun_ak_secret
        });
      }
      if (typeof values.aliyun_isi_appkey != "undefined") {
        data.push({
          key: "aliyun_isi_appkey",
          value: values.aliyun_isi_appkey
        });
      } else if (cacheISI) {
        data.push({
          key: "aliyun_isi_appkey",
          value: setting.aliyun_isi_appkey
        });
      }
      if (typeof values.aliyun_bucket_name != "undefined") {
        data.push({
          key: "aliyun_bucket_name",
          value: values.aliyun_bucket_name
        });
      }
      if (this.sub == 1 || typeof this.sub == "undefined") {
        data.push({
          key: "upload_oss",
          value: this.upload_oss ? "true" : "false"
        });
      }

      if (this.sub == 2 || typeof this.sub == "undefined") {
        data.push({
          key: "tts_voice",
          value: this.tts_voice
        });
        data.push({
          key: "tts_speech",
          value: this.tts_speech.toString()
        });
        data.push({
          key: "tts_pitch",
          value: this.tts_pitch.toString()
        });
        data.push({
          key: "tts_volume",
          value: this.tts_volume.toString()
        });
      }
      return data;
    },
    submitSettings() {
      //e.preventDefault();
      this.formSettings.validateFields((err, values) => {
        if (err) {
          this.formCheck = 1;
        } else {
          let data = this.formToData(values);
          this.$api.setting
            .setList(data)
            .then(() => {
              this.$message.info("设置已经生效！");
            })
            .catch(err => {
              console.log(err);
            });
        }
      });
    },
    checkedUpload() {
      this.upload_oss = !this.upload_oss;
    },
    handleCheckAliyun() {
      var values = this.formSettings.getFieldsValue();
      //console.log(e);
      let data = this.formToData(values);
      this.$api.test
        .checkSetList(data)
        .then(res => {
          if (res.aliyun_ak_secret) {
            this.test.aliyunAccess = 0;
          }
          if (res.aliyun_isi_appkey) {
            this.test.aliyunISIAppKey = 0;
          }
          if (res.aliyun_bucket_name) {
            this.test.aliyunOSS = 0;
          }
          if (
            res.aliyun_ak_secret &&
            res.aliyun_isi_appkey &&
            res.aliyun_bucket_name
          ) {
            this.formCheck = 0;
          }
        })
        .catch(err => {
          if (err.data.error == 1301) {
            this.test.aliyunAccess = 1;
          }
          if (err.data.error == 1302) {
            this.test.aliyunISIAppKey = 1;
          }
          if (err.data.error == 1303) {
            this.test.aliyunOSS = 1;
          }
          this.formCheck = 1;
          //console.log(err);
        });
    },
    handleListOSS() {
      if (this.test.aliyunAccess == 0) {
        var values = this.formSettings.getFieldsValue();
        let data = [];
        if (
          typeof values.aliyun_ak_id != "undefined" &&
          typeof values.aliyun_ak_secret != "undefined"
        ) {
          data.push({
            key: "aliyun_ak_id",
            value: values.aliyun_ak_id
          });
          data.push({
            key: "aliyun_ak_secret",
            value: values.aliyun_ak_secret
          });

          this.$api.setting.getOSSList(data).then(resOSS => {
            this.dataSource.oss = [];
            resOSS.forEach(v => {
              this.dataSource.oss.push(
                v.Name + "." + v.Location + ".aliyuncs.com"
              );
            });
          });
        }
      }
    },
    handleTestTTS(e) {
      //console.log(e)
      let innerHTML = e.target.innerHTML
      e.target.textContent = "生成中...";
      var values = this.formSettings.getFieldsValue();
      let data = this.formToData(values, true);
      data.push({
        key: "tts_test",
        value: this.tts_test
      });
      this.$api.test.checkSetList(data).then(res => {
        this.sound = res.wav+"?t="+Date.parse( new Date());
        e.target.innerHTML = innerHTML;
      });
    },
    setTextTTS() {
      let setting = JSON.parse(
        JSON.stringify(this.$store.state.common.setting)
      );
      setting["tts_test"] = this.tts_test;
      this.$store.commit("SETTING", setting);
    }
  }
};
</script>

<style lang="less" scoped>
.wav_player{      
      overflow: hidden;
      .audio{      
      height: 20px;
      //background: #f0f2f5;
      width: 280px;
      margin-left:-10px;     
    }
    }
    .tts_test{
      border-style: dashed
    }
</style>